﻿using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Webcar.BLL;
using Webcar.Utils;
using Webcar.Entitys;
using System.Data;
using System.Xml;
using System.Text;
using System.Xml.Serialization;
using System.Transactions;
namespace Webcar.Controllers
{
    public partial class SystemController : BaseControler
    {
        public ActionResult UpdateFile()
        {
            CurrentUser.EnsureAdmin();
            return View();
        }
        [HttpPost]
        public ActionResult UnzipUpdateFile()
        {
            
            CurrentUser.EnsureAdmin();
            var files = Request.Files;
            if (files.Count == 0)
                throw new Exception("没有找到上传的文件。");
            var file = files[0];
            if (file.ContentLength == 0) return null;

            string fileext = Path.GetExtension(file.FileName).ToLower();
            if (fileext!=".zip")
            {
                throw new Exception("该格式的附件不能上传。");
            }
            this.Unzip(file.InputStream, Server.MapPath("~"));
            return Success("UpdateFile", "System");
        }
        private void Unzip(Stream zip_stream, string out_folder)
        {
            using (ZipInputStream s = new ZipInputStream(zip_stream))
            {
                ZipEntry theEntry;
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    string directoryName = Path.GetDirectoryName(theEntry.Name);
                    string fileName = Path.GetFileName(theEntry.Name);
                    if (directoryName.Length > 0)
                    {
                        Directory.CreateDirectory(Path.Combine(out_folder,directoryName));
                    }
                    if (!directoryName.EndsWith("\\"))
                        directoryName += "\\";
                    if (fileName != String.Empty)
                    {
                        string filename = Path.Combine(out_folder,theEntry.Name);
                        using (FileStream streamWriter = System.IO.File.Create(filename))
                        {
                            int size = 2048;
                            byte[] data = new byte[2048];
                            while (true)
                            {
                                size = s.Read(data, 0, data.Length);
                                if (size > 0)
                                {
                                    streamWriter.Write(data, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                        }
                    }
                }//while
            }

        }
        public ActionResult Update()
        {
            CurrentUser.EnsureAdmin();
            return View(model:"");
        }
        [HttpPost]
        public ActionResult ExecuteUpdate(string update_sql)
        {
            try
            {
                CurrentUser.EnsureAdmin();
                if (update_sql.IsNull())
                {
                    ViewBag.ExecuteMessage = "请输入执行的语句。";
                    return View("Update", model: update_sql);
                }
                Webcar.Entitys.WebcarDataProvider.DB.ObjectContext.ExecuteStoreCommand(update_sql);
                ViewBag.ExecuteMessage = "执行成功。";
                
            }
            catch (Exception ex)
            {
                ViewBag.ExecuteMessage = "执行失败:"+ex.Message;
            }
            return View("Update",model: update_sql);
        }
        [HttpPost]
        public ActionResult Import()
        {
#if DEBUG
            string filename = Server.MapPath("~/aaaaaabs_files.zip");
            var bytes = System.IO.File.ReadAllBytes(filename);
            var list = JsonHelper.PraseFromJsonZip<List<bs_files>>(bytes);
            //using (TransactionScope transaction = new TransactionScope())
            //{
            using (var DB = new WebcarContext())
            {
                foreach (var item in list)
                {
                    DB.bs_files.Add(item);
                }
                DB.SaveChanges();
            }
                //transaction.Complete();
            //}
           
#endif
            return View();
            
        }
        [HttpPost]
        public ActionResult ExportDeptXls()
        {
            var table = WebcarDataProvider.DB.bs_files.ToList();

            byte[] zip = JsonHelper.GetJsonZip(table);
            string filename = Server.MapPath("~/bs_files.zip");
            System.IO.File.WriteAllBytes(filename, zip);
            return new RedirectResult("~/bs_files.zip");
        }
        [HttpPost]
        public ActionResult ExportCarXls()
        {
            var table = WebcarDataProvider.DB.BS_CAR_RECORD.ToList();

            byte[] zip = JsonHelper.GetJsonZip(table);
            string filename = Server.MapPath("~/BS_CAR_RECORD.zip");
            System.IO.File.WriteAllBytes(filename, zip);
            return new RedirectResult("~/BS_CAR_RECORD.zip");
        }
        [HttpPost]
        public ActionResult ExportUserXls()
        {
            var table = WebcarDataProvider.DB.BS_EMP.ToList();

            byte[] zip = JsonHelper.GetJsonZip(table);
            string filename = Server.MapPath("~/BS_EMP.zip");
            System.IO.File.WriteAllBytes(filename, zip);
            return new RedirectResult("~/BS_EMP.zip");
        }

         private static string SerializeXml(DataTable pDt) {
              // 序列化DataTable
              StringBuilder sb = new StringBuilder();
              XmlWriter writer = XmlWriter.Create(sb);
             XmlSerializer serializer = new XmlSerializer(typeof(DataTable));
             serializer.Serialize(writer, pDt);
             writer.Close();
             return sb.ToString();
        }
    }
}